package com.gitee.xmhzzz.component.oss.token;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gitee.xmhzzz.component.oss.config.OssConfig;
import lombok.Builder;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName OssTankenContext
 * @Description
 * @Author wzq
 * @Date 2023/7/19 15:35
 * @Version 1.0
 */
public class OssSecurityTokenContext {

    private static final Logger log = LoggerFactory.getLogger(OssSecurityTokenContext.class);

    private OssConfig ossConfig;

    public OssSecurityTokenContext(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    public  OssTokenDTO getSecurityToken() {
        try {
            // regionId表示RAM的地域ID。以华东1（杭州）地域为例，regionID填写为cn-hangzhou。也可以保留默认值，默认值为空字符串（""）。
            String regionId = "cn-shenzhen";
            // 添加endpoint。适用于Java SDK 3.12.0及以上版本。
            DefaultProfile.addEndpoint(regionId, ossConfig.getBucketName(), ossConfig.getEndpoint());
            // 构造default profile。
            IClientProfile profile = DefaultProfile.getProfile(regionId, ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            // 构造client。
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            // 适用于Java SDK 3.12.0及以上版本。
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(ossConfig.getRoleArn());
            request.setRoleSessionName(ossConfig.getRoleSessionName());
            // 如果policy为空，则用户将获得该角色下所有权限。
            // 设置临时访问凭证的有效时间为3600秒。
            request.setDurationSeconds(3600L);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            return OssTokenDTO.builder()
                    .AccessKeyId(response.getCredentials().getAccessKeyId())
                    .AccessKeySecret(response.getCredentials().getAccessKeySecret())
                    .SecurityToken(response.getCredentials().getSecurityToken())
                    .build();
        } catch (Exception e) {
            log.error("请求阿里云oss拿到临时token异常描述：{}", e.getMessage(), e);
        }
        return null;
    }


    @Data
    @Builder
    public static class OssTokenDTO{
        private String SecurityToken;
        private String AccessKeySecret;
        private String AccessKeyId;
    }

}
